﻿using System;
using System.Linq;
using Enyim.Caching;
using Ayatta.Contract;
using System.Web.Mvc;
using Web.Core.Security;
using Web.Seller.Models;
using Web.Core.Extensions;
using Web.Core.Components;
using Ayatta.Contract.Domain;
using Ayatta.Common.Extension;

namespace Web.Seller.Controllers
{
    public class OrderController : BaseController
    {
        public OrderController(Lazy<IInfrastructureService> infrastructure, Lazy<IPassportService> passport, Lazy<IAccountService> account, Lazy<IStoreService> store, Lazy<ITradeService> trade, Lazy<IPlayService> play, Lazy<IMiscService> misc, Lazy<IExtraService> extra, IMemcachedClient memcachedClient)
            : base(infrastructure, passport, account, store, trade, play, misc, extra, memcachedClient)
        {
        }

        /// <summary>
        /// 订单列表
        /// </summary>
        /// <param name="page">当前页</param>
        /// <param name="size">分页大小</param>
        /// <param name="id">订单号</param>
        /// <param name="name">商品标题</param>
        /// <param name="buyer">买家Id/用户名</param>
        /// <param name="category">分类</param>
        /// <param name="status">订单状态</param>
        /// <param name="comment">评论状态</param>
        /// <param name="beginDate">开始时间</param>
        /// <param name="endDate">结束时间</param>
        /// <returns></returns>
        public ActionResult Index(int page = 1, int size = 20, string id = null, string name = null, string buyer = null, OrderCategory category = OrderCategory.Normal, OrderStatus? status = null, byte? comment = null, DateTime? beginDate = null, DateTime? endDate = null)
        {
            var identity = User.Identity.Identity();
            var model = new OrderControllerModel.Index();

            int buyerId;
            var buyerName = int.TryParse(buyer, out buyerId) ? null : buyer;

            model.Id = id;
            model.Name = name;
            model.Buyer = buyer;
            model.Category = category;
            model.Status = status;
            model.Comment = comment;

            var orders = Trade.Value.OrderPagedList(page, size, id, name, true, identity.Id, buyerName, category, status, comment, beginDate, endDate).ToPagedList(page, size);

            model.Orders = orders;
            return View(model);
        }
        /// <summary>
        /// 订单详细信息
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Detail(string param)
        {
            var identity = User.Identity.Identity();
            var model = new OrderControllerModel.Detail();
            var order = Trade.Value.GetOrder(param, identity.Id, true, true);
            model.Order = order;
            if (order.Status == OrderStatus.SellerSendPart || order.Status == OrderStatus.WaitBuyerConfirm ||
               order.Status == OrderStatus.Finished)
            {
                model.Shippings = Trade.Value.OrderShipmentGet(param);
            }
            return View(model);
        }
        /// <summary>
        /// 订单备忘
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Memo(string param)
        {
            var identity = User.Identity.Identity();
            var model = Trade.Value.GetOrderMemo(param, identity.Id, true);
            return PartialView(model);
        }

        /// <summary>
        /// 订单备忘
        /// </summary>
        /// <param name="param">订单号</param>
        /// <param name="flag">Flag</param>
        /// <param name="memo">备忘</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Memo(string param, byte? flag, string memo)
        {
            var result = new MagicKit<string>();
            if (memo.Length > 100)
            {
                result.Message = "备忘不能超过100个字！";
                return Json(result);
            }
            if (Request.IsAuthenticated)
            {
                var identity = User.Identity.Identity();
                var status = Trade.Value.UpdateOrderMemo(param, identity.Id, true, flag, memo);
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = "备忘失败！";
                }
            }
            else
            {
                result.Message = "请登录！";
            }
            return Json(result);
        }

        /// <summary>
        /// 修改收货地址
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Address(string param)
        {
            var identity = User.Identity.Identity();
            var model = new OrderControllerModel.Address();

            var order = Trade.Value.GetOrder(param, identity.Id, false, true);
            if (order.Shipment != OrderShipment.Virtual)
            {
                var areas = AreaList();
                var areaId = order.AreaId;
                var p = areaId.Substring(0, 2);
                var c = areaId.Substring(0, 4);
                //bug mvc DropDownList name不能为 province
                model.Province = new SelectList(areas.Where(o => o.Group == 1 && o.ParentId == "0"), "Id", "Name", p);
                model.City = new SelectList(areas.Where(o => o.Group == 2 && o.ParentId == p), "Id", "Name", c);
                model.District = new SelectList(areas.Where(o => o.Group == 3 && o.ParentId == c), "Id", "Name", areaId);

            }
            model.Order = order;
            return PartialView(model);
        }

        /// <summary>
        /// 修改订单地址
        /// </summary>
        /// <param name="param">订单号</param>
        /// <param name="receiver">收货地址</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Address(string param, UserAddress receiver)
        {
            var result = new MagicKit<string>();
            if (receiver.AreaId.IsNullOrEmpty())
            {
                result.Message = "请选择所在地区！";
                return Json(result);
            }
            var identity = User.Identity.Identity();
            if (Request.IsAuthenticated)
            {
                var order = Trade.Value.GetOrder(param, identity.Id, false, true);
                if (order.Status != OrderStatus.WaitSellerSend)
                {
                    result.Message = "当前订单状态不可修改收货信息！";
                }
                else
                {
                    if (receiver.Name.IsNullOrEmpty())
                    {
                        result.Message = "请填写收货人的姓名！";
                        return Json(result);
                    }
                    if (receiver.Address.IsNullOrEmpty())
                    {
                        result.Message = "请填写收货人的详细地址！";
                        return Json(result);
                    }
                    if (receiver.Mobile.IsNullOrEmpty() && receiver.Phone.IsNullOrEmpty())
                    {
                        result.Message = "电话和手机请至少填写一个！";
                        return Json(result);
                    }
                    if (!receiver.Phone.IsNullOrEmpty() && !receiver.Phone.IsPhone())
                    {
                        result.Message = "请填写正确的电话号码！";
                        return Json(result);
                    }
                    if (!receiver.Mobile.IsNullOrEmpty() && !receiver.Mobile.IsMobile())
                    {
                        result.Message = "请填写正确的手机号码！";
                        return Json(result);
                    }
                    if (!receiver.PostalCode.IsPostalCode())
                    {
                        result.Message = "请填写正确的邮政编码！";
                        return Json(result);
                    }
                    var areas = AreaFullName(receiver.AreaId, AreaList());
                    receiver.Province = areas.First;
                    receiver.City = areas.Second;
                    receiver.District = areas.Third;
                    var status = Trade.Value.UpdateOrderAddress(param, identity.Id, true, receiver);
                    if (status)
                    {
                        result.Status = true;
                    }
                    else
                    {
                        result.Message = "修改收货信息失败！";
                    }
                }
            }
            else
            {
                result.Message = "请登录！";
            }
            return Json(result);
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="param">订单号</param>
        /// <returns></returns>
        public ActionResult Cancel(string param)
        {
            var identity = User.Identity.Identity();
            var model = new MagicKit<Order>();
            if (Request.IsAuthenticated)
            {
                var order = Trade.Value.OrderStatusGet(param, identity.Id, true);
                if (order == null)
                {
                    model.Message = "订单不存在！";
                }
                else
                {
                    if (order.Status == OrderStatus.Pending || order.Status == OrderStatus.WaitBuyerPay)
                    {
                        model.Status = true;
                        model.Data = order;
                    }
                    else
                    {
                        model.Message = "该订单当前状态不可关闭交易！";
                    }
                }
            }
            else
            {
                model.Message = "登录超时请重新登录！";
            }
            return PartialView(model);
        }

        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="param">订单号</param>
        /// <param name="reason">取消原因</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Cancel(string param, string reason)
        {
            var result = new MagicKit<Order>();
            var identity = User.Identity.Identity();
            var order = Trade.Value.OrderStatusGet(param, identity.Id, true);
            if (order == null)
            {
                result.Message = "订单不存在！";
                return Json(result);
            }
            if (order.Status == OrderStatus.Pending || order.Status == OrderStatus.WaitBuyerPay)
            {
                var status = Trade.Value.OrderStatusUpdate(param, identity.Id, true, OrderStatus.Canceled, reason);
                if (status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = "取消订单失败！";
                }
            }
            else
            {
                result.Message = "该订单当前状态不可取消！";
            }
            return Json(result);
        }

        /// <summary>
        /// 延长收货时间
        /// </summary>
        /// <returns></returns>
        public ActionResult Delay(string param)
        {
            var identity = User.Identity.Identity();
            var model = new MagicKit<Order>();
            if (Request.IsAuthenticated)
            {
                var order = Trade.Value.OrderStatusGet(param, identity.Id, true);
                if (order == null)
                {
                    model.Message = "订单不存在！";
                }
                else
                {
                    if (order.Status != OrderStatus.WaitBuyerConfirm)
                    {
                        model.Message = "该订单当前状态不可延长收货时间！";
                    }
                    else
                    {
                        model.Status = true;
                        model.Data = order;
                    }
                }
            }
            else
            {
                model.Message = "登录超时请重新登录！";
            }
            return PartialView(model);
        }

        /// <summary>
        /// 延长收货时间
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delay(string param, int day)
        {
            var result = new MagicKit<string>();
            var identity = User.Identity.Identity();
            if (Request.IsAuthenticated)
            {
                if (day.IsIn(new[] { 3, 5, 7, 10 }))
                {
                    var order = Trade.Value.OrderStatusGet(param, identity.Id, true);
                    if (order == null)
                    {
                        result.Message = "订单不存在！";
                        return Json(result);
                    }
                    if (order.Status == OrderStatus.WaitBuyerConfirm)
                    {
                        var status = Trade.Value.UpdateOrderExpiration(param, identity.Id, day);
                        if (status)
                        {
                            result.Status = true;
                        }
                        else
                        {
                            result.Message = "取消订单失败！";
                        }
                    }
                    else
                    {
                        result.Message = "该订单当前状态不可延长收货时间！";
                    }
                }
                else
                {
                    result.Message = "参数不正确！";
                }
            }
            else
            {
                result.Message = "登录超时请重新登录！";
            }
            return Json(result);
        }

        public ActionResult Edit(string param)
        {
            return PartialView();
        }

        /// <summary>
        /// 发货
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ActionResult Consign(string param)
        {
            var identity = User.Identity.Identity();
            var model = new OrderControllerModel.Consign();
            var order = Trade.Value.GetOrder(param, identity.Id, true, true);
            if (order != null)
            {
                if (order.Status == OrderStatus.WaitSellerSend || order.Status == OrderStatus.SellerSendPart)
                {
                    var areas = AreaList();
                    var addresses = UserAddressList(identity.Id).Where(o => o.Category != AddressCategory.Receive).ToList();

                    model.Areas = areas;
                    model.Order = order;
                    model.Addresses = addresses;
                    model.LogisticsCompanies = LogisticsCompanyList();
                    model.DefaultSendAddress = addresses.FirstOrDefault(o => o.Category == AddressCategory.Send && o.IsDefault);
                    model.DefaultRefundAddress = addresses.FirstOrDefault(o => o.Category == AddressCategory.Refund && o.IsDefault);
                    var areaId = order.AreaId;
                    var p = areaId.Substring(0, 2);
                    var c = areaId.Substring(0, 4);

                    model.Province = new SelectList(areas.Where(o => o.Group == 1 && o.ParentId == "0"), "Id", "Name", p);
                    model.City = new SelectList(areas.Where(o => o.Group == 2 && o.ParentId == p), "Id", "Name", c);
                    model.District = new SelectList(areas.Where(o => o.Group == 3 && o.ParentId == c), "Id", "Name", areaId);

                    model.Shippings = new string[0];
                    if (order.Status == OrderStatus.SellerSendPart)
                    {
                        var temp = Trade.Value.GetSplitShippingOrderId(param);
                        if (!temp.IsNullOrEmpty())
                        {
                            model.Shippings = temp.Split(',');
                        }
                    }
                }
                else
                {
                    var url = WebSite.Seller + "/order/detail/" + order.Id;
                    return Redirect(url);
                }
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Consign(string param, string[] subId, int sendAddressId, int refundAddressId, string expressNo, string extra, UserAddress receiver)
        {
            var time = DateTime.Now;
            var identity = User.Identity.Identity();
            var result = new MagicKit<string>();

            if (subId == null || subId.Length < 1)
            {
                result.Message = "请选择待发货的商品！";
                return Json(result);
            }
            var order = Trade.Value.GetOrder(param, identity.Id, true, true);
            if (order.Status == OrderStatus.WaitSellerSend || order.Status == OrderStatus.SellerSendPart)
            {

                var items = order.OrderItems.Where(o => o.Status != OrderStatus.Canceled && o.Status != OrderStatus.Closed).ToArray();
                var itemIds = items.Select(o => o.Id).ToArray();
                foreach (var id in subId)
                {
                    if (itemIds.Contains(id)) continue;
                    result.Data = id;
                    result.Message = "参数错误！";
                    return Json(result);
                }

                var shipment = new Shipment();
                var shipmentExtra = new ShipmentExtra();
                var shipmentId = IdGenerate(time, order.BuyerId, order.SellerId);

                shipment.Id = shipmentId;
                shipmentExtra.Id = shipmentId;

                var areas = AreaList();
                var area = AreaFullName(order.AreaId, areas);
                shipment.Category = 0;
                shipment.OrderId = order.Id;

                shipment.ExpressNo = expressNo;
                shipment.Title = string.Empty;
                shipment.Summary = string.Empty;
                shipment.IsQuickCod = false;
                shipment.DeliveryStart = null;
                shipment.DeliveryEnd = null;
                shipment.Payer = "seller";

                shipment.Receiver = receiver.Name;
                shipment.Company = string.Empty;
                shipment.Phone = receiver.Phone.IfNullEmpty();
                shipment.Mobile = receiver.Mobile.IfNullEmpty();
                shipment.AreaId = receiver.AreaId;
                shipment.Province = area.First;
                shipment.City = area.Second;
                shipment.District = area.Third;
                shipment.Address = receiver.Address;
                shipment.PostalCode = receiver.PostalCode;
                shipment.CompanyId = 0;
                shipment.CompanyName = string.Empty;
                shipment.SenderId = order.BuyerId;
                shipment.ReceiverId = order.BuyerId;
                shipment.ReceiverName = order.CreatedBy;
                shipment.Extra = extra.IfNullEmpty();
                shipment.Status = ShippingStatus.Created;
                shipment.CreatedBy = User.Identity.Name;
                shipment.CreatedOn = time;

                var addresses = UserAddressList(identity.Id);
                var sendAddress = addresses.FirstOrDefault(o => o.Id == sendAddressId);
                if (sendAddress != null)
                {
                    area = AreaFullName(sendAddress.AreaId, areas);
                    shipmentExtra.Sender = sendAddress.Name;
                    shipmentExtra.Company = sendAddress.Company.IfNullEmpty();
                    shipmentExtra.Phone = sendAddress.Phone.IfNullEmpty();
                    shipmentExtra.Mobile = sendAddress.Mobile.IfNullEmpty();
                    shipmentExtra.AreaId = sendAddress.AreaId;
                    shipmentExtra.Province = area.First;
                    shipmentExtra.City = area.Second;
                    shipmentExtra.District = area.Third;
                    shipmentExtra.Address = sendAddress.Address;
                    shipmentExtra.PostalCode = sendAddress.PostalCode;
                }
                else
                {
                    result.Message = "发货地址不正确！";
                    return Json(result);
                }
                var refundAddress = addresses.FirstOrDefault(o => o.Id == refundAddressId);
                if (refundAddress != null)
                {
                    area = AreaFullName(refundAddress.AreaId, areas);
                    shipmentExtra.Receiver = refundAddress.Name;
                    shipmentExtra.ReceiverCompany = refundAddress.Company.IfNullEmpty();
                    shipmentExtra.ReceiverPhone = refundAddress.Phone.IfNullEmpty();
                    shipmentExtra.ReceiverMobile = refundAddress.Mobile.IfNullEmpty();
                    shipmentExtra.ReceiverAreaId = refundAddress.AreaId;
                    shipmentExtra.ReceiverProvince = area.First;
                    shipmentExtra.ReceiverCity = area.Second;
                    shipmentExtra.ReceiverDistrict = area.Third;
                    shipmentExtra.ReceiverAddress = refundAddress.Address;
                    shipmentExtra.ReceiverPostalCode = refundAddress.PostalCode;
                }
                else
                {
                    result.Message = "退货地址不正确！";
                    return Json(result);
                }
                shipment.ShipmentExtra = shipmentExtra;

                if (order.Status == OrderStatus.WaitSellerSend)
                {
                    if (items.Length == subId.Length)
                    {
                        shipment.OrderItemId = itemIds.ToString(',');
                        order.Status = OrderStatus.WaitBuyerConfirm;
                    }
                    else
                    {
                        order.MultipleConsign = true;
                        shipment.OrderItemId = subId.ToString(',');
                        order.Status = OrderStatus.SellerSendPart;
                    }
                }
                else if (order.Status == OrderStatus.SellerSendPart)
                {
                    var ids = Trade.Value.GetSplitShippingOrderId(order.Id).Split(',');
                    foreach (var id in subId)
                    {
                        if (!ids.Contains(id)) continue;
                        result.Data = id;
                        result.Message = "商品{0}已发货！";
                        return Json(result);
                    }
                    shipment.OrderItemId = subId.ToString(',');
                    if (itemIds.Length == ids.Length + subId.Length)
                    {
                        order.Status = OrderStatus.WaitBuyerConfirm;
                    }

                }
                var magic = Trade.Value.OrderShipmentCreate(order.Id, shipment.OrderItemId, order.Status, identity.Id, order.MultipleConsign, shipment);
                if (magic.Status)
                {
                    result.Status = true;
                }
                else
                {
                    result.Message = magic.Message;
                }
            }
            else
            {
                result.Message = "订单状态错误！";
            }
            return Json(result);
        }
    }
}
